
package com.toman.ui.work.workshop;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.itheima.pulltorefreshlib.PullToRefreshBase;
import com.itheima.pulltorefreshlib.PullToRefreshScrollView;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.GetRequest;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.NetworkEnum;
import com.toman.Enum.PermEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.ReceiveSendworkOrderDto;
import com.toman.JavaBean.StaticsCount;
import com.toman.R;
import com.toman.Util.ActionCallback;
import com.toman.Util.BaseNetUtil;
import com.toman.Util.DialogUtils;
import com.toman.Util.IntentUtils;
import com.toman.Util.JsonExcludeNull;
import com.toman.Util.JsonUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.DialogBean;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.ClearEditText;
import com.toman.widget.callback.StringLoadingCallback;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;

public class GetActivity extends ToolBarActivity {

    @BindView(R.id.et_search)
    ClearEditText etSearch;
    @BindView(R.id.tv_select)
    TextView tvSelect;
    @BindView(R.id.fl_et)
    RelativeLayout flEt;
    @BindView(R.id.tv_select0)
    TextView tvSelect0;
    @BindView(R.id.iv_select0)
    ImageView ivSelect0;
    @BindView(R.id.rl_select0)
    RelativeLayout rlSelect0;
    @BindView(R.id.tv_select1)
    TextView tvSelect1;
    @BindView(R.id.iv_select1)
    ImageView ivSelect1;
    @BindView(R.id.rl_select1)
    RelativeLayout rlSelect1;
    @BindView(R.id.ll_base)
    LinearLayout llBase;
    @BindView(R.id.cb_muti)
    CheckBox cbMuti;
    @BindView(R.id.btn_muti)
    Button btnMuti;
    @BindView(R.id.rl_muti)
    RelativeLayout rlMuti;
    @BindView(R.id.lv)
    RecyclerView lv;
    @BindView(R.id.mPullToRefreshScrollView)
    PullToRefreshScrollView mPullToRefreshScrollView;
    @BindView(R.id.mMangeNodata)
    TextView mMangeNodata;

    private List<ReceiveSendworkOrderDto> list = new ArrayList<>();
    private String receiveStatus = "0";
    CommonAdapter<ReceiveSendworkOrderDto> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get);
        ButterKnife.bind(this);
        initView();
        initToolBar(BaseEnum.GET.name);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!StringUtils.isEmpty(getIntent().getStringExtra("status"))){
            p_id=(getIntent().getStringExtra("etSearch"));
            setStatus(getIntent().getStringExtra("status"));
        } else {
            customer(1, 1, etSearch.getText().toString());
        }
    }


    private void initView() {
        baseEnum=BaseEnum.GET;
        btnMuti.setText("一键领取");
        etSearch.setHint("派工单号/品号/品名");

        initAdapter();
        cbMuti.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).isCanRecevie()){
                    list.get(i).setCheckStatus(b);}
                }
                adapter.notifyDataSetChanged();
            }
        });
        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                List<ReceiveSendworkOrderDto> beanlist = adapter.getDatas();
                ReceiveSendworkOrderDto bean = beanlist.get(position);
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", bean);
                bundle.putString("status", receiveStatus);
                IntentUtils.startActivity(GetActivity.this, GetInfActivity.class, bundle);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        lv.setAdapter(adapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) {
        };
        lv.setLayoutManager(linearLayoutManager);
        mPullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        mPullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                dialog=null;
                dialogList.clear();
                p_id=null;

                page = 2;
                customer(1, 1, etSearch.getText().toString().trim());
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                customer(page, 2, etSearch.getText().toString().trim());
                page += 1;


            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                customer(1, 1, s.toString().trim());

            }
        });

    }

    private void initAdapter() {
        adapter = new CommonAdapter<ReceiveSendworkOrderDto>(this, R.layout.item_workshop_get, list) {
            @Override
            protected void convert(ViewHolder holder, ReceiveSendworkOrderDto item, final int position) {
                holder.setText(R.id.tv_time, item.getSendworkorderEntity().getCreateTime());
                holder.setText(R.id.tv_code, item.getSendworkorderEntity().getSendworkCode());
                holder.setText(R.id.tv_no, item.getOperationorderEntity().getOrderName());
                holder.setText(R.id.tv_product_name, item.getProductEntity().getProductName());

                holder.setText(R.id.tv_dep, item.getPlanEntity().getPlanNum());
                holder.setText(R.id.tv_beltline, item.getBeltlineEntity().getBeltlineName());
                holder.setText(R.id.tv_need, item.getSendworkOrderMappingEntity().getWorkCount() + "");
                holder.setText(R.id.tv_dispatching, item.getSendworkorderEntity().getSendworkCount() + "");
                holder.getView(R.id.btn_look_first).setOnClickListener(v -> lookFirst(item));
                holder.getView(R.id.btn_look_more).setOnClickListener(v -> lookMore(item));

//                派工单状态
                if (item.getSendworkorderEntity().getOrderStatus().equals("0")) {
                    holder.setImageResource(R.id.iv_status, R.mipmap.icon_jxz);
                } else if (item.getSendworkorderEntity().getOrderStatus().equals("1")) {
                    holder.setImageResource(R.id.iv_status, R.mipmap.icon_ztz);
                } else {
                    holder.setImageResource(R.id.iv_status, R.mipmap.icon_yjs);
                }

                if (item.getSendworkOrderMappingEntity().getReceiveStatus().equals("0")) {
                    CheckBox checkBox = holder.getView(R.id.cb_status);
                    checkBox.setChecked(item.getCheckStatus());
                    checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> item.setCheckStatus(isChecked));
                    holder.getView(R.id.cb_status).setVisibility(View.VISIBLE);
                    holder.getView(R.id.btn_del).setVisibility(View.GONE);
                    if (item.getSendworkorderEntity().getOrderStatus().equals("0")) {
                        holder.getView(R.id.btn_get).setVisibility(View.VISIBLE);
                    } else {
                        holder.getView(R.id.btn_get).setVisibility(View.GONE);
                    }
//                    领工
                    holder.getView(R.id.btn_get).setOnClickListener(v -> mutiCheckDialog(item.getMappingId() + ""));
                    holder.getView(R.id.btn_look_first).setVisibility(View.GONE);
                    holder.getView(R.id.btn_look_more).setVisibility(View.GONE);
                } else if (item.getSendworkOrderMappingEntity().getReceiveStatus().equals("1")) {
                    holder.getView(R.id.cb_status).setVisibility(View.GONE);
                    holder.getView(R.id.btn_get).setVisibility(View.GONE);
                    holder.getView(R.id.btn_del).setVisibility(View.GONE);
                    holder.getView(R.id.btn_look_first).setVisibility(View.VISIBLE);
                    holder.getView(R.id.btn_look_more).setVisibility(View.VISIBLE);
                    holder.setText(R.id.tv_finish, item.getArleadyReceiveSendworkOrderCount().getCompletedCount() + "");
                }
                if (!item.isCanRecevie()) {
                    holder.getView(R.id.btn_get).setVisibility(View.GONE);
                }
//

            }
        };
    }

    public void customer(Integer page, final Integer type, String search) {
        if (dialog != null) {
            dialog.dismiss();
        }


        GetRequest params = OkHttpUtils
                .get(NewBaseUrl.workshop_get_list)
                .params("token", token)
                .params("key", search)
                .params("limit", NewBaseUrl.num).params("page", page.toString())
                .params("id",p_id)
                .params("receiveStatus", receiveStatus);
        for (DialogBean bean: dialogList){
            params.params(bean.getSubmitName(),bean.getResult());
        }
        params        .execute(new StringLoadingCallback(this,mPullToRefreshScrollView,search) {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "领工列表: " + result);
                        if (type == 1) {
                            list.clear();
                        }
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
                            JSONObject Jpage = jsonObj.getJSONObject("page");

                            List<ReceiveSendworkOrderDto> jsonArray = new ArrayList<ReceiveSendworkOrderDto>(JsonExcludeNull.parseArrayExcludeNull(Jpage.getString("list"), ReceiveSendworkOrderDto.class));
                            list.addAll(jsonArray);

                            if (list.size() == 0) {
                                mMangeNodata.setVisibility(View.VISIBLE);
                            } else {
                                mMangeNodata.setVisibility(View.GONE);
                            }


                            adapter.notifyDataSetChanged();
                            StaticsCount count = JSON.parseObject(Jpage.getString("staticsCount"), new TypeReference<StaticsCount>() {
                            });
                            tvSelect0.setText("待领取(" + count.getCount0() + ")");
                            tvSelect1.setText("已领取(" + count.getCount1() + ")");
                            setCbMuti();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                        mPullToRefreshScrollView.onRefreshComplete();
                    }
                });
    }

    private void setStatus(String status) {
        this.status=status;
        switch (status) {
            case "0":
                receiveStatus = "0";
                tvSelect0.setTextColor(getResources().getColor(R.color.button_blue));
                tvSelect1.setTextColor(getResources().getColor(R.color.black33));
                ivSelect0.setBackgroundColor(getResources().getColor(R.color.button_blue));
                ivSelect1.setBackgroundColor(getResources().getColor(R.color.white));
                customer(1, 1, etSearch.getText().toString());

                break;
            case "1":
                receiveStatus = "1";
                tvSelect1.setTextColor(getResources().getColor(R.color.button_blue));
                tvSelect0.setTextColor(getResources().getColor(R.color.black33));
                ivSelect1.setBackgroundColor(getResources().getColor(R.color.button_blue));
                ivSelect0.setBackgroundColor(getResources().getColor(R.color.white));
                customer(1, 1, etSearch.getText().toString());
                break;


        }
    }
    private void setCbMuti(){
        switch (status){
            case "0":
                if (getCheck()==null){
                    rlMuti.setVisibility(View.GONE);
            }
            else {rlMuti.setVisibility(View.VISIBLE);}
                cbMuti.setChecked(false);
            break;
            case "1":
                rlMuti.setVisibility(View.GONE);
                break;
        }
    }


//    public void setSelect(String select) {
//        switch (select) {
//            case "0":
//                setStatus("1");
//                break;
//            case "1":
//                setStatus("0");
//                break;
//
//        }
//    }

    public void mutiCheckDialog(final String ids) {

        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化

        new AlertDialog.Builder(this)
                //对话框的标题
                .setTitle("确认领取选中的派工信息吗？")
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", (dialog, whichButton) -> check(ids))
                .setNegativeButton("取消", (dialog, which) -> {

                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();

    }
    public void mutiCheckDialogNew(final String ids) {

        //LayoutInflater是用来找layout文件夹下的xml布局文件，并且实例化

        new AlertDialog.Builder(this)
                //对话框的标题
                .setTitle("确认一键领取选中的派工信息吗？")
                //设定显示的View
                //对话框中的“登陆”按钮的点击事件
                .setPositiveButton("确认", (dialog, whichButton) -> check(ids))
                .setNegativeButton("取消", (dialog, which) -> {

                })
                // 设置dialog是否为模态，false表示模态，true表示非模态
                .setCancelable(true)
                //对话框的创建、显示
                .create().show();

    }

    private String getMutiCheck() {
        StringBuilder stringBuffer = new StringBuilder();

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getCheckStatus() && list.get(i).getSendworkorderEntity().getOrderStatus().equals("0")) {

                if (stringBuffer.length() <= 0) {
                    stringBuffer.append(list.get(i).getMappingId());
                } else {
                    stringBuffer.append(",").append(list.get(i).getMappingId());
                }
            }

        }
        if (stringBuffer.length() <= 0) {
            return null;
        } else {
            return stringBuffer.toString();
        }

    }
    private String getCheck() {
        StringBuilder stringBuffer = new StringBuilder();

        for (int i = 0; i < list.size(); i++) {
            if ( list.get(i).getSendworkorderEntity().getOrderStatus().equals("0")&&list.get(i).isCanRecevie()) {

                if (stringBuffer.length() <= 0) {
                    stringBuffer.append(list.get(i).getMappingId());
                } else {
                    stringBuffer.append(",").append(list.get(i).getMappingId());
                }
            }

        }
        if (stringBuffer.length() <= 0) {
            return null;
        } else {
            return stringBuffer.toString();
        }

    }


    private void check(String ids) {


        Map<String, String> map = new HashMap<String, String>();

        map.put("ids", ids);

        String str = JsonUtils.obj2JsonString(map);
        OkHttpUtils
                .post(NewBaseUrl.workshop_get_get + ids)
                .headers("token", token)
                .postJson(str)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "领取派工信息: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                        if (code == 0) {
                            ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
                            customer(1, 1, "");


                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    private void lookMore(ReceiveSendworkOrderDto entity) {
        Bundle bundle = new Bundle();
        bundle.putString("status", "1");
        bundle.putString("isfirstReport","0");
        bundle.putString("mappingId", entity.getMappingId() + "");
        IntentUtils.startActivity(GetActivity.this, SubmitActivity.class, bundle);
    }

    private void lookFirst(ReceiveSendworkOrderDto entity) {
        Bundle bundle = new Bundle();
        bundle.putString("status", "1");
        bundle.putString("isfirstReport","1");
        bundle.putString("mappingId", entity.getMappingId() + "");
        IntentUtils.startActivity(GetActivity.this, SubmitActivity.class, bundle);
    }

    @OnClick({R.id.rl_select0, R.id.rl_select1, R.id.btn_muti})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_select0:
                setStatus("0");
                break;
            case R.id.rl_select1:
                setStatus("1");
                break;
            case R.id.btn_muti:
                if (getMutiCheck() == null) {
                    ToastUtil.makeText(getApplicationContext(), "请至少选中一个可领取选项或者有选项不可领取");
                } else {
                    mutiCheckDialogNew(getMutiCheck());
                }
                break;
        }
    }

    @OnClick(R.id.tv_select)
    public void onViewClicked() {
    showDialog();

    }
    public void showDialog() {
        if (dialog == null) {
            dialogList.clear();
            dialogList.add( new DialogBean("productId","品名", 1, BaseNetUtil.base(this, NetworkEnum.PRODUCT, mCompanyId)));
            dialogList.add( new DialogBean("artlineId","工艺路线名称", 1, BaseNetUtil.base(this, NetworkEnum.ARTLINE, mCompanyId)));
            dialogList.add( new DialogBean("beltlineId","产线名称", 1, BaseNetUtil.base(this, NetworkEnum.BELTLINE, mCompanyId)));


            dialog = DialogUtils.selectNewDialog(this, dialogList, new ActionCallback() {
                @Override
                public void run() {
                    customer(1, 1,"");
                    dialog.dismiss();

                }
            });
            dialog.show();
        } else {
            dialog.show();
        }
    }

}
